import { AppComponentBase } from '@shared/common/app-component-base';
import { AuthorityInfoDTO } from '@shared/service-proxy/service-proxies';
import { Component, OnInit, Injector } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { ServiceProxy } from '@shared/service-proxy/service-proxies';

export interface TreeNodeInterface {
  key: string;
  name: string;
  parent: string;
  level: number;
  expand: boolean;
  children?: TreeNodeInterface[];
}

@Component({
  selector: 'app-permission-management',
  templateUrl: './permission-management.component.html',
  styleUrls: ['./permission-management.component.less']
})

export class PermissionManagementComponent extends AppComponentBase implements OnInit {

  permissions = [];
  dataSet = [];
  data = [];
  loading = true;
  isVisible = false;
  accreditShow = false;
  isOkLoading = false;
  title: string;
  parentName: string;
  constructor(injector: Injector,
    private fb: FormBuilder,
    private _service: ServiceProxy) {
    super(injector);
  }

  model: AuthorityInfoDTO = new AuthorityInfoDTO();
  validateForm;

  searchData(): void {
    this.loading = true;
    this._service.getAllAuthorityInfosUsingGET().subscribe(result => {
      this.dataSet = result.result.fieldList;
      this.loading = false;

      this.data = [];
      this.buildTree();

      this.data.forEach(item => {
        this.expandDataCache[item.key] = this.convertTreeToList(item);
      });
    });
  }

  buildTree() {
    this.getRootNodes();
    this.buildChildNodes(this.data);
  }

  buildChildNodes(parentList: any[]) {

    parentList.forEach(m => {
      const nodes = this.dataSet.filter(z => z.parentCode == m.code);
      nodes.forEach(n => {
        if (!m.children) {
          m.children = [];
        }
        m.children = [...m.children, {
          id: n.id,
          key: n.code,
          name: n.name,
          parentCode: n.parentCode,
          code: n.code,
        }];

        this.buildChildNodes(m.children);
      });
      // this.buildChildNodes(nodes);
    });
  }

  getRootNodes() {
    const rootList = this.dataSet.filter(m => m.parentCode == "ROOT_");
    rootList.forEach(m => {
      this.data = [...this.data, {
        id: m.id,
        key: m.code,
        name: m.name,
        parentCode: m.parentCode,
        code: m.code,
      }];
    });
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
    });
    this.searchData();

  }
  showModal(id?: string, data?: AuthorityInfoDTO): void {
    this.isVisible = true;
    if (id) {
      this.title = this.l("edit");
      this.parentName = '';
      this._service.getAuthorityInfoUsingGET(id).subscribe(result => {
        this.model = result.result;
      });
    } else if (data) {
      this.model = new AuthorityInfoDTO();
      this.validateForm.reset();
      this.model.parentCode = data.code;
      this.parentName = data.name;
    } else {
      this.parentName = '';
      this.validateForm.reset();
      this.title = this.l("create");
    }
  }

  submitForm(): void {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.valid) { // 验证通过
      if (this.model.id) {
        this._service.updateAuthorityInfoUsingPUT(this.model, this.model.id).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l('save_success'));
            this.isVisible = false;
            this.searchData();
          }
          else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoading = false;
          this.message.error(this.l(error.message));
        }
        )
      }
      else {
        this._service.createAuthorityInfoUsingPOST(this.model).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l('save_success'));
            this.isVisible = false;
            this.searchData();
          }
          else {
            this.message.info(this.l(result.error.message));
          }


        }, error => {
          this.isOkLoading = false;
          this.message.error(this.l(error.message));
        })
      }

    } else { // 验证未通过
      this.isOkLoading = false;
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }

  }
  handleOk(): void {
    this.submitForm();
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }

  mouseAction(name: string, e: any): void {
    console.log(name, e);
  }

  // tslint:disable-next-line:member-ordering
  expandDataCache = {};

  collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void {
    if ($event === false) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.key === d.key);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: object): TreeNodeInterface[] {
    const stack = [];
    const array = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level + 1, expand: false, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node: TreeNodeInterface, hashMap: object, array: TreeNodeInterface[]): void {
    if (!hashMap[node.key]) {
      hashMap[node.key] = true;
      array.push(node);
    }
  }

}
